package socketwork1;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;//套接字
    public Client(){
        try {
            System.out.println("客户端启动,正在连接服务器...");
            socket = new Socket("localhost",8088);//创建一个Socket对象,指定服务器的IP和端口号
            System.out.println("连接成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 启动客户端
    public void start()  {
        try {
            // 启动一个线程用于读取来自服务端的消息
            ServerHandler handler = new ServerHandler();//创建一个ServerHandler对象
            Thread t = new Thread(handler);//创建一个线程对象
            t.start();//启动线程

            // 向服务端发送消息
            OutputStream out = socket.getOutputStream();// 获取输出流, 向服务器输出
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);//编码
            BufferedWriter bw = new BufferedWriter(osw);//缓冲
            PrintWriter pw = new PrintWriter(bw,true);//自动行刷新
            //pw.println("你好服务器");
            Scanner scan = new Scanner(System.in);//创建一个扫描器
            System.out.println("请输入你要发送的内容: ");//提示
            while(true){
                String line = scan.nextLine();//扫描器扫描输入的内容
                if("exit".equalsIgnoreCase(line)){//控制台输入exit结束客户端
                    break;
                }
                pw.println(line);//发送
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();//进行了四次挥手
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();//创建一个Client对象
        client.start();//启动客户端
    }

    private class ServerHandler implements Runnable{
        public void run(){
            try {
                InputStream in = socket.getInputStream();//获取输入流
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);//编码, 默认UTF-8
                BufferedReader br = new BufferedReader(isr);//缓冲
                String message;//读取
                while((message=br.readLine())!=null){//循环读取, 直到读取到null退出循环
                    System.out.println(message);//输出
                }
            } catch (Exception e) {
            }
        }
    }
}
